package com.coocaa.ops.admin.v1.timedtask.job;

import com.coocaa.ops.admin.v1.timedtask.biz.TimedTaskBizImpl;
import com.coocaa.ops.common.core.base.util.MyAppContextUtil;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * @author bijiahao
 * @description
 * @date 2020/5/13 17:41
 */
public abstract class AbstractQuartzJob implements Job {

    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
    protected TimedTaskBizImpl timedTaskBiz;

    public AbstractQuartzJob() {
        this.timedTaskBiz = MyAppContextUtil.getBean("timedTaskBizImpl", TimedTaskBizImpl.class);
        Assert.notNull(timedTaskBiz, "timedTaskBizImpl 没有注入成功");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        Assert.notNull(jobDetail, "JobDetail-任务信息没有设置");
        JobDataMap dataMap = jobDetail.getJobDataMap();
        Assert.notNull(dataMap, "JobDataMap-任务信息没有设置");
        Integer resourceId = null;
        try {
            resourceId = dataMap.getIntValue("resourceId");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("===resourceId 不能为: " + dataMap.getString("resourceId"));
        }
        TimedTaskInfoEntity entity = this.queryTimedTaskInfoEntity(resourceId);
        if (null == entity) {
            //如果没有对应定时任务，说明该任务已被取消 直接返回
            return;
        }
        log.info(String.format("====定时版面强插更新任务,resourceType: %s,resourceId: %s,resourceVersion: %s", entity.getResourceType(), entity.getResourceId(), entity.getResourceVersion()));

        //处理定时任务
        this.handleTimedTask(entity);
    }

    /**
     * 查询定时信息
     *
     * @param resourceId
     * @return
     */
    abstract protected TimedTaskInfoEntity queryTimedTaskInfoEntity(Integer resourceId);

    /**
     * 处理定时任务
     *
     * @param entity
     */
    abstract protected void handleTimedTask(TimedTaskInfoEntity entity);

}
